package org.bintrotter.contentmanager;

import static org.junit.Assert.*;

import org.junit.Test;

public class UnitTest {
	

	@Test public void TestScope() {
		
		// Content manager with depth 8 should be able to store 0 <= x < 2^8
		ContentManager manager = new ContentManager(8);
		
		boolean threwException;
		
		threwException = false;
		try { manager.set(0); }
		catch(Exception e) { threwException = true; }
		assertFalse(threwException);
		
		threwException = false;
		try { manager.set(255); }
		catch(Exception e) { threwException = true; }
		assertFalse(threwException);
		
		threwException = false;
		try { manager.set(256); }
		catch(Exception e) { threwException = true; }
		assertTrue(threwException);
		
		threwException = false;
		try { manager.set(512); }
		catch(Exception e) { threwException = true; }
		assertTrue(threwException);
		
		manager = null;
	}
	
	@Test public void TestCleanup() throws Exception {
		
		// Content manager should automatically delete redundant nodes.
		final int depth = 4;
		ContentManager manager = new ContentManager(depth);

		// A single set should need only as many nodes as depth, and one extra leaf.
		manager.set(0);
		
		assertTrue( manager.countLeaves() == depth+1);
		assertTrue( manager.countNodes()  == depth);
		
		// add a few, then remove to that only 1 different leaf is set.
		manager.set(7);
		manager.set(6);
		manager.unset(6);
		manager.unset(0);
		
		// tree SHOULD have returned to initial size.
		assertTrue( manager.countLeaves() == depth+1);
		assertTrue( manager.countNodes()  == depth);
		
		manager = null;
	}
	
	@Test public void TestStorage() throws Exception {
		
		final long depth = 16;
		final long max = (long) Math.pow(2, depth);
		ContentManager manager = new ContentManager((int) depth);
		
		for(long l=0; l<max; ++l)
			assertFalse( manager.isSet(l));
		
		for(long l=0; l<max; ++l)
			if((((l>>8) % 3) == 0) && (((l&0xff) % 3) == 0))
				manager.set(l);
		
		for(long l=0; l<max; ++l)
			if((((l>>8) % 3) == 0) && (((l&0xff) % 3) == 0))
				assertTrue(manager.isSet(l));
			else
				assertFalse(manager.isSet(l));
				
		for(long l=0; l<max; ++l)
			if(l>(max/2))
				manager.set(l);
			else
				manager.unset(l);
		
		for(long l=0; l<max; ++l)
			if(l>(max/2))
				assertTrue(manager.isSet(l));
			else
				assertFalse(manager.isSet(l));
		
		manager = null;
	}
	
	

}

